package com.gome.ss.webserver.servlet.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gome.ss.common.AppConfiguer;
import com.gome.ss.flowcrawl.extractor.FlowCrawlExtractor;
import com.gome.ss.flowcrawl.extractor.FlowCrawlExtractorManager;
import com.gome.ss.flowcrawl.extractor.FlowCrawlExtractorStatus;
import com.gome.ss.flowcrawl.plugin.FlowCrawlManager;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

public class FlowCrawlExtractGet extends HttpServlet {
	
	/* /spiderkit/flowcrawl_extract_get */
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String pluginName = req.getParameter("pluginName");
		String stepID = req.getParameter("stepID");
		resp.setContentType("text/html;charset=gbk");
		req.setCharacterEncoding("gbk");
		
		if (!pluginName.isEmpty()) {
			BasicDBObject query = new BasicDBObject("name", pluginName);
			query.append("stepID", stepID);
			DBCollection collection = AppConfiguer.flowCrawlConfigMongo.getDB(AppConfiguer.FLOWCRAWL_DB_NAME)
					 .getCollection(AppConfiguer.FLOWCRAWL_EXTRACT_COLLECTION_NAME);
			DBCursor cursor = collection.find(query);
			
			List<DBObject> array = new ArrayList<DBObject>();
			
			FlowCrawlExtractor extrator = FlowCrawlExtractorManager.getInstance().getExtractor(pluginName, stepID);
			boolean isExtracting = false;
			if (extrator != null)
				isExtracting = extrator.getStatus().getStatus() == FlowCrawlExtractorStatus.STATUS_START ? true : false;
			
			while(cursor.hasNext()) {
				DBObject obj = cursor.next();
				obj.put("isExtracting", isExtracting);
				array.add(obj);
			}
			resp.getWriter().print(JSON.serialize(array));
			resp.getWriter().close();
		}

		resp.getWriter().print(AppConfiguer.NULL_JSON_ARRAY);
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(req, resp);
	}

}
